from watchdog.events import *
from watchdog.observers import Observer
from flask import current_app
from .. import config as CONFIG
from .controllers import parse_config


def create_observer(config_name):
    observer = Observer()
    event_handler = FileEventHandler()
    observer.schedule(event_handler, CONFIG[config_name].WATCHED_DIR, True)
    return observer


class FileEventHandler(PatternMatchingEventHandler):
    def __init__(self):
        PatternMatchingEventHandler.__init__(self, patterns=["*.cfg"], ignore_directories=True)
        self.app = current_app._get_current_object()

    def on_moved(self, event):
        print("file moved from {0} to {1}".format(event.src_path, event.dest_path))

    def on_created(self, event):
        try:
            parse_config(event.src_path, self.app)
        except Exception as e:
            print(str(e))
        print("file created:{0}".format(event.src_path))

    def on_deleted(self, event):
        try:
            parse_config(event.src_path, self.app)
        except Exception as e:
            print(str(e))
        print("file deleted:{0}".format(event.src_path))

    def on_modified(self, event):
        try:
            parse_config(event.src_path, self.app)
        except Exception as e:
            print(str(e))
        print("file modified:{0}".format(event.src_path))
